/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bff.core.action.retrieve;

import com.inspur.edp.bff.api.dataprocessor.IDataConvertor;
import com.inspur.edp.bff.api.manager.IFSManager;
import com.inspur.edp.bff.api.manager.SourceConfig;
import com.inspur.edp.bff.spi.AbstractFSAction;
import com.inspur.edp.cef.api.action.EditResult;
import com.inspur.edp.cef.entity.accessor.entity.IEntityAccessor;
import com.inspur.edp.cef.entity.entity.IEntityData;
import lombok.var;

import java.util.ArrayList;

public class EditAction extends AbstractFSAction<EditResult> {

    private String dataID;

    public EditAction(String dataID) {
        this.dataID = dataID;
    }

    @Override
    protected void execute() {
        setResult(new EditResult());
        ArrayList<SourceConfig> config = getContext().getSourceConfigs();
        if (config != null && config.size() == 1) {
            doDefaultEdit();
        }
    }

    private void doDefaultEdit() {
        EditResult retriveResult = getLcp().edit(dataID);
        IEntityData beData = retriveResult.getData();
        if (beData != null) {
            IDataConvertor dataConvertor = getContext().getDataConvertor();
            IFSManager bffManager = getContext().getBffManager();
            IEntityData vmData = bffManager.createData();
            IEntityAccessor vmAccessor = (IEntityAccessor) ((vmData instanceof IEntityAccessor) ? vmData : null);
            IEntityData voData = (IEntityData) ((vmAccessor.getInnerData() instanceof IEntityData) ? vmAccessor.getInnerData() : null);
            dataConvertor.convertFromBEData(beData, voData);

            dealExtendData(voData, beData);

            vmAccessor.setInnerData(voData);

            getResult().setData((IEntityData) ((vmAccessor.getInnerData() instanceof IEntityData) ? vmAccessor.getInnerData() : null));
        }
    }

    private void dealExtendData(IEntityData voData, IEntityData beData) {
        var extList = getContext().getExtList();
        if (extList == null || extList.size() < 1)
            return;
        for (var ext : extList) {
            ext.mapData2Vo(voData, beData);
        }
    }
}
